from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exempt
from bbs.forms import BbsForm, CommentForm, CreateComment, CreateBbs
from bbs.models import Bbs
from service.tools import Tools
from django.core.paginator import Paginator


def index(request):
    title = '主页-社区-量子企业数据智能分析系统-专注企业加速'
    page = int(request.GET.get("page", 1))
    bbs = Bbs.objects.all().order_by("-create_time")
    pag = Paginator(bbs, 10)
    bbs_list = pag.page(page)
    page_arr = Tools.paginator(page, pag)
    left = page_arr.get("left")
    right = page_arr.get("right")
    url = "/bbs?page="
    return render(request, 'bbs/index.html', locals())


def new(request):
    title = '发表新帖-社区-量子企业数据智能分析系统-专注企业加速'
    if request.method == "POST":
        bbs = CreateBbs(request.POST)
        if bbs.is_valid():
            id = bbs.save().pk
            return redirect('show', id)
        else:
            message = Tools.format_errors('bbs', bbs.errors)
            return render(request, 'bbs/new.html', locals())
    else:
        bbs = BbsForm(request.POST)
        return render(request, 'bbs/new.html', locals())


def show(request, id):
    bbs = Bbs.objects.filter(pk=id)[0]
    title = bbs.title + '-社区-量子企业数据智能分析系统-专注企业加速'
    pag = Paginator(bbs.comment_set.all(), 2)
    comments = pag.page(1)
    comment = CommentForm(request.POST)
    count = bbs.comment_set.count()
    return render(request, 'bbs/show.html', locals())


# ajax 翻页回帖
def ajax_comments(request, bbs_id):
    page = int(request.GET.get("page", 1))
    pag = Paginator(Bbs.objects.filter(pk=bbs_id)[0].comment_set.all().order_by('-create_time'), 2)
    comment_list = pag.page(page)
    if page <= pag.num_pages:
        return render(request, 'bbs/ajax_comments.html', locals())
    else:
        return JsonResponse({'msg': 'true'})


# 回帖
@csrf_exempt
def new_comment(request):
    if request.method == 'POST':
        comment = CreateComment(request.POST)
        if comment.is_valid():
            com = comment.save()
            return render(request, 'bbs/show_comments.html', locals())
        else:
            return JsonResponse({'msg': 'true', 'result': Tools.format_errors('bbs', comment.errors)})


def bbs_map(request):
    return render(request, 'bbs/bbs_map.html')